import router from './router';
import store from './store';
import { Message } from 'element-ui';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getAccessToken } from '@/utils/auth';
import { isRelogin } from '@/utils/request';
import { removeTenantId, setTenantId, setToken } from './utils/auth';

NProgress.configure({ showSpinner: false });

router.beforeEach((to, from, next) => {
	// 如果地址栏的参数
	if (to.query.token) {
		setToken({
			accessToken: `${to.query.token}`,
			refreshToken: `${to.query.token}`
		});
	}
	if (to.query.tenantId) {
		setTenantId(to.query.tenantId);
	}
	NProgress.start();
	/* has token*/
	if (getAccessToken()) {
		to.meta.title && store.dispatch('settings/setTitle', to.meta.title);
		if (to.path === '/login') {
			next({ path: '/' });
			NProgress.done();
		} else {
			if (store.getters.roles.length === 0) {
				store.dispatch('dict/loadDictDatas');
				isRelogin.show = true;
				// 先获取用户info信息
				store.dispatch('GetInfo').then(() => {
					isRelogin.show = false;
					// 再去获取路由权限信息
					store.dispatch('GenerateRoutes').then(accessRoutes => {
						// 根据roles权限生成可访问的路由表
						router.addRoutes(accessRoutes);
						next({ ...to, replace: true });
					});
				}).catch(err => {
					store.dispatch('LogOut').then(() => {
						Message.error(err);
						next({ path: '/' });
					});
				});
			} else {
				next();
			}
		}
	} else {
		if (to.path !== '/login') {
			removeTenantId();
			next('/login');
		} else {
			next();
		}
	}
});

router.afterEach(() => {
  NProgress.done();
});
